package com.dsl.dslsuzhou.engine;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 时间轴填充工具
 */
public class FillUtil {
    
    /**
     * 生成时间序列CTE SQL
     */
    public static String generateTimeSeriesCte(TimeRange timeRange, Granularity granularity) {
        List<String> timePoints = generateTimePoints(timeRange, granularity);
        
        StringBuilder cte = new StringBuilder();
        cte.append("WITH time_series AS (\n");
        
        for (int i = 0; i < timePoints.size(); i++) {
            if (i > 0) {
                cte.append("  UNION ALL\n");
            }
            cte.append("  SELECT '").append(timePoints.get(i)).append("' AS bucket\n");
        }
        
        cte.append(")");
        return cte.toString();
    }
    
    /**
     * 生成时间点列表
     */
    private static List<String> generateTimePoints(TimeRange timeRange, Granularity granularity) {
        List<String> points = new ArrayList<>();
        LocalDateTime current = timeRange.getStart();
        LocalDateTime end = timeRange.getEnd();
        
        DateTimeFormatter formatter = getFormatter(granularity);
        
        while (current.isBefore(end)) {
            points.add(current.format(formatter));
            current = addTime(current, granularity);
        }
        
        return points;
    }
    
    /**
     * 根据粒度获取格式化器
     */
    private static DateTimeFormatter getFormatter(Granularity granularity) {
        switch (granularity) {
            case HOUR:
                return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:00:00");
            case DAY:
                return DateTimeFormatter.ofPattern("yyyy-MM-dd");
            case MONTH:
                return DateTimeFormatter.ofPattern("yyyy-MM-01");
            default:
                throw new IllegalArgumentException("Unsupported granularity: " + granularity);
        }
    }
    
    /**
     * 根据粒度增加时间
     */
    private static LocalDateTime addTime(LocalDateTime dateTime, Granularity granularity) {
        switch (granularity) {
            case HOUR:
                return dateTime.plusHours(1);
            case DAY:
                return dateTime.plusDays(1);
            case MONTH:
                return dateTime.plusMonths(1);
            default:
                throw new IllegalArgumentException("Unsupported granularity: " + granularity);
        }
    }
}
